package com.dd.da.config.auth;

import com.dd.dc.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述: 认证服务器
 * EnableAuthorizationServer
 * @author: yanglin
 * @Date: 2021-03-05-13:56
 * @Version: 1.0
 */
@Configuration
@EnableAuthorizationServer
public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private static final int ACCESS_TOKEN_TIMER = 60 * 60 * 24;

    private static final int REFRESH_TOKEN_TIMER = 60 * 60 * 24 * 30;

    /**
     * 注入AuthenticationManager ，密码模式用到
     */
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    @Qualifier("JWTTokenStore")
    private TokenStore tokenStore;

    /**
     * JWT 生成Token
     */
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    /**
     * 扩展JWT
     */
    @Autowired
    private TokenEnhancer jwtTokenEnhancer;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单认证
        security.allowFormAuthenticationForClients();
    }

    /**
     * 客户端配置（给谁发令牌）
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("internet_plus")
                // internet_plus
                // 解決oauth/token 401问题,secret加密
                .secret(passwordEncoder().encode("internet_plus"))
                //设置支持[密码模式、授权码模式、token刷新]
                .authorizedGrantTypes(
                        "password",
                        "authorization_code",
                        "refresh_token")
                //  Token 失效时间
                .accessTokenValiditySeconds(ACCESS_TOKEN_TIMER)
                //  Token 刷新时间
                .refreshTokenValiditySeconds(REFRESH_TOKEN_TIMER)
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                // 1.未扩展配置JWT
                .tokenStore(tokenStore);
                // 规定token生成器是jwtAccessTokenConverter，并按照我们设置的签名来生成。
                // .accessTokenConverter(jwtAccessTokenConverter);
        // 2.扩展配置JWT 增强器链对象TokenEnhancerChain
        // 重写TokenEnhancer的enhance方法，根据需求扩展jwt。
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = new ArrayList<>();
        enhancerList.add(jwtTokenEnhancer);
        enhancerList.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(enhancerList);
        endpoints
                .tokenEnhancer(enhancerChain)
                .accessTokenConverter(jwtAccessTokenConverter);
    }

    /**
     *
     @Bean
     public PasswordEncoder passwordEncoder(){
     return new BCryptPasswordEncoder();
     }
     */
    /**
     * 自定义加密方式
     * charSequence是用户输入的密码，password是存库的密码
     * 解决Handling error: InvalidRequestException, Missing grant type
     * 修改ajax' Content-Type':'application/x-www-form-urlencoded'
     * 重写PasswordEncoder  接口中的方法，实例化加密策略,返回 BCrypt 加密策略
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return MD5Util.getMD5(charSequence.toString());
            }

            @Override
            public boolean matches(CharSequence charSequence, String password) {
                return password.contentEquals(encode(charSequence));
            }
        };
    }
}
